
cd "`c(pwd)'"   // Set working directory to wherever the user placed "replication_package"

* Define global paths relative to the main directory
global main_dir "`c(pwd)'"
global data_dir "$main_dir/data_analysis"
global rawdata_dir "$main_dir/data_raw"
global tables_dir "$main_dir/tables"

cd "$rawdata_dir/"

use patent_kogan, clear

gen year=substr(filing_date,-4,4)
destring   year, replace
bys permno year: egen num_pat_filing=count(patent_num)
bys permno year: egen valtot_pat_filing=sum(xi_real)
bys permno year: egen valavg_pat_filing=mean(xi_real)
bys permno year: egen citetot_pat_filing=sum(cites)
bys permno year: egen citeavg_pat_filing=mean(cites)

collapse (mean) num_pat_filing valtot_pat_filing valavg_pat_filing citetot_pat_filing citeavg_pat_filing , by(permno  year)

joinby permno year using gvkey_permno_year, unmatched(master)
tab _merge
drop _merge

cd "$rawdata_dir/"
save patents_filing, replace

